package pixelwaks.plugins.modes;

import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;

import common.core.Tile;
import common.util.Calculate;


import pixelwaks.core.impl.Game;
import pixelwaks.core.impl.Player;
import pixelwaks.ctrl.ControlFactory;
import pixelwaks.ctrl.impl.PlayerCtrl;
import pixelwaks.plugins.GameMode;

public class VSMode extends GameMode {
	
	@Override
	public boolean projectileHitSomething(Point p) {
		
		return hitPlayer(p.x, p.y);
	}

	@Override
	public boolean isGameOver() {
		
		int counter = 0;

		for(Player p: Game.getInstance().getPlayers())
			if(p.getStatus() > 0)
				counter++;
		
		boolean b = counter == 1;
		
		if(b)
			setGameOverInfo(whoWonTheGame().getName() + " won the game!");
		
		return b;
	}
	
	@Override
	public void otherHitByExplosion(Point p, int strength) {

		checkIfPlayerGotHitByExplosion(p, strength);    
	}
	
	private void checkIfPlayerGotHitByExplosion(Point p, int strength) {

		int radius = strength * Tile.TILE_SIZE + (Tile.TILE_SIZE / 2);

		for(Player player: Game.getInstance().getPlayers()) {
			BufferedImage body = player.getBody();
			int height = body.getHeight();
			int width = body.getWidth();
			Raster raster = body.getRaster();
			int[] array = null;

			for (int y = 0; y < height; y++)
				for (int x = 0; x < width; x++)
					if (Calculate.isInBlastArea(p.x, p.y, player.getPosition().x + x,
							player.getPosition().y - height + y, radius))
						if (raster.getPixel(x, y, array)[3] != 0) {
							PlayerCtrl pctrl = (PlayerCtrl) ControlFactory.getObserver(ControlFactory.PLAYER_CTRL);
							pctrl.setStatus(player, player.getStatus()-0.02);
						}
		}
	}

	private boolean hitPlayer(int x, int y) {
		
		for(Player player: Game.getInstance().getPlayers()) {
			
			int height = player.getBody().getHeight();
			int width = player.getBody().getWidth();
			Raster raster = player.getBody().getRaster();
			int[] array = null;

			if(x > player.getPosition().x && x < player.getPosition().x + width
				&& y > player.getPosition().y - height && y < player.getPosition().y) {
				
				int imgX = x - player.getPosition().x;
				int imgY = height - (player.getPosition().y - y);
				
				if(raster.getPixel(imgX, imgY, array)[3] != 0)
					return true;
			}
		}
		return false;
	}
	
	private Player whoWonTheGame() {
		
		Player player = null;
		for(Player p: Game.getInstance().getPlayers())
			if(p.getStatus() > 0)
				player = p;
		
		return player;
	}
}

